using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class HealthBarUI : MonoBehaviour

{
    [SerializeField]
    public GameObject healthUIPrefab;
    public Transform barPoint;
    public CharacterDataHolder currentStats;

    private Transform UIbar;
    private Image healthSlider;
    private Text healthText;
    private Image defenceImage;
    private Text defenceText;
    private Text courageText;
    private DamageText damageText;
    private void Awake()
    {
        currentStats.UpdateHealthOnAttack += UpdateHealthBar;
        currentStats.UpdateDefenceOnAttack += UpdateDefenceText;
        currentStats.UpdateCourageOnAttack += UpdateCourageText;
        currentStats.ShowDamageOnAttack += CreateDamageText;
    }

    private void UpdateHealthBar(int currentHealth, int maxHealth)
    {
        if (currentHealth <= 0)
        {
            //die
        }
        float sliderPercent = (float)currentHealth / maxHealth;
        healthSlider.fillAmount = sliderPercent;
        healthText.text = currentHealth.ToString()+"/"+maxHealth.ToString();
    }

    private void UpdateDefenceText(int currentDefence)
    {
        if(currentDefence<=0)
        {
            defenceImage.gameObject.SetActive(false);
        }
        else
        {
            defenceImage.gameObject.SetActive(true);
            defenceText.text = currentDefence.ToString();
        }
    }

    private void UpdateCourageText(int currentCourage,int maxCourage)
    {
        if(currentStats.CharacterID==0)
        {
            courageText.gameObject.SetActive(true);
            courageText.text = currentCourage.ToString() + "/" +maxCourage.ToString();
        }
    }

    private void CreateDamageText(int damage)
    {
        DamageText text = Instantiate(damageText, UIbar.transform);
        text.ChangeText(damage);
    }

    private void OnEnable()
    {
        foreach (Canvas canvas in FindObjectsOfType<Canvas>())
        {
            if (canvas.renderMode == RenderMode.WorldSpace)//查找方式可以不一样根据需求
            {
                UIbar = Instantiate(healthUIPrefab, canvas.transform).transform;
                HealthBarImage healthBarInUIBar = UIbar.GetComponent<HealthBarImage>();
                healthText = healthBarInUIBar.healthText;
                healthSlider = healthBarInUIBar.healthImage;
                defenceText = healthBarInUIBar.defenceText;
                defenceImage = healthBarInUIBar.defenceImage;
                courageText = healthBarInUIBar.courageText;
                damageText = healthBarInUIBar.damageText;
            }
        }
    }

    private void LateUpdate()
    {
        if(UIbar!=null)
        {
            UIbar.position = barPoint.position;
        }
    }
}
